package com.woniuxy.realm;

import com.woniuxy.entity.User;
import com.woniuxy.entity.Venue;
import com.woniuxy.service.VenueService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;
/**
 * 吴毛伟原生态制造
 */
public class VenueRealm extends AuthorizingRealm {
    @Autowired
    private VenueService venueService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roles = new HashSet<>();
        roles.add("venue");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1. 把AuthenticationToken转换为CustomizedToken
        CustomizedToken customizedToken = (CustomizedToken) token;
        // 2. 从CustomizedToken中获取用户名
//        String vname = (String) customizedToken.getPrincipal();
        String vname = customizedToken.getUsername();
        // 3. 若用户不存在，抛出UnknownAccountException异常
        Venue venueByVname = venueService.findVenueByVname(vname);
        if (venueByVname == null) {
            throw new UnknownAccountException("场馆不存在！");
        }
        // 4.
        // 根据用户的情况，来构建AuthenticationInfo对象并返回，通常使用的实现类为SimpleAuthenticationInfo
        // 以下信息从数据库中获取
        // （1）principal：认证的实体信息，可以是vname，也可以是数据表对应的用户的实体类对象
        String principal = vname;
        // （2）credentials：密码
        String credentials = new SimpleHash("MD5", venueByVname.getPwd(), vname, 1024).toString();
        // （3）realmName：当前realm对象的name，调用父类的getName()方法即可
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials,
                realmName);
        return info;
    }

}
